<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 4.2.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/safari-pinned-tab.svg" color="#222">
  <link rel="stylesheet" href="/css/main.css">
  <link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>
  <script id="hexo-configurations">
    var NexT = window.NexT ||
    {};
    var CONFIG = {
      "hostname": "cuiqingcai.com",
      "root": "/",
      "scheme": "Pisces",
      "version": "7.8.0",
      "exturl": false,
      "sidebar":
      {
        "position": "right",
        "width": 360,
        "display": "post",
        "padding": 18,
        "offset": 12,
        "onmobile": false,
        "widgets": [
          {
            "type": "image",
            "name": "阿布云",
            "enable": false,
            "url": "https://www.abuyun.com/http-proxy/introduce.html",
            "src": "https://qiniu.cuiqingcai.com/88au8.jpg",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "天验",
            "enable": true,
            "url": "https://tutorial.lengyue.video/?coupon=12ef4b1a-a3db-11ea-bb37-0242ac130002_cqx_850",
            "src": "https://qiniu.cuiqingcai.com/bco2a.png",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "华为云",
            "enable": false,
            "url": "https://activity.huaweicloud.com/2020_618_promotion/index.html?bpName=5f9f98a29e2c40b780c1793086f29fe2&bindType=1&salesID=wangyubei",
            "src": "https://qiniu.cuiqingcai.com/y42ik.jpg",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "张小鸡",
            "enable": false,
            "url": "http://www.zxiaoji.com/",
            "src": "https://qiniu.cuiqingcai.com/fm72f.png",
            "width": "100%"
      },
          {
            "type": "image",
            "name": "Luminati",
            "src": "https://qiniu.cuiqingcai.com/ikkq9.jpg",
            "url": "https://luminati-china.io/?affiliate=ref_5fbbaaa9647883f5c6f77095",
            "width": "100%",
            "enable": false
      },
          {
            "type": "image",
            "name": "IPIDEA",
            "url": "http://www.ipidea.net/?utm-source=cqc&utm-keyword=?cqc",
            "src": "https://qiniu.cuiqingcai.com/0ywun.png",
            "width": "100%",
            "enable": true
      },
          {
            "type": "tags",
            "name": "标签云",
            "enable": true
      },
          {
            "type": "categories",
            "name": "分类",
            "enable": true
      },
          {
            "type": "friends",
            "name": "友情链接",
            "enable": true
      },
          {
            "type": "hot",
            "name": "猜你喜欢",
            "enable": true
      }]
      },
      "copycode":
      {
        "enable": true,
        "show_result": true,
        "style": "mac"
      },
      "back2top":
      {
        "enable": true,
        "sidebar": false,
        "scrollpercent": true
      },
      "bookmark":
      {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": true,
      "comments":
      {
        "style": "tabs",
        "active": "gitalk",
        "storage": true,
        "lazyload": false,
        "nav": null,
        "activeClass": "gitalk"
      },
      "algolia":
      {
        "hits":
        {
          "per_page": 10
        },
        "labels":
        {
          "input_placeholder": "Search for Posts",
          "hits_empty": "We didn't find any results for the search: ${query}",
          "hits_stats": "${hits} results found in ${time} ms"
        }
      },
      "localsearch":
      {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 10,
        "unescape": false,
        "preload": false
      },
      "motion":
      {
        "enable": false,
        "async": false,
        "transition":
        {
          "post_block": "bounceDownIn",
          "post_header": "slideDownIn",
          "post_body": "slideDownIn",
          "coll_header": "slideLeftIn",
          "sidebar": "slideUpIn"
        }
      },
      "path": "search.xml"
    };

  </script>
  <meta name="description" content="Python 是支持面向对象的，很多情况下使用面向对象编程会使得代码更加容易扩展，并且可维护性更高，但是如果你写的多了或者某一对象非常复杂了，其中的一些写法会相当相当繁琐，而且我们会经常碰到对象和 JSON 序列化及反序列化的问题，原生的 Python 转起来还是很费劲的。 可能这么说大家会觉得有点抽象，那么这里举几个例子来感受一下。 首先让我们定义一个对象吧，比如颜色。我们常用 RGB 三个原色">
  <meta property="og:type" content="article">
  <meta property="og:title" content="Python 使用 attrs 和 cattrs 实现面向对象编程">
  <meta property="og:url" content="https://cuiqingcai.com/6552.html">
  <meta property="og:site_name" content="静觅">
  <meta property="og:description" content="Python 是支持面向对象的，很多情况下使用面向对象编程会使得代码更加容易扩展，并且可维护性更高，但是如果你写的多了或者某一对象非常复杂了，其中的一些写法会相当相当繁琐，而且我们会经常碰到对象和 JSON 序列化及反序列化的问题，原生的 Python 转起来还是很费劲的。 可能这么说大家会觉得有点抽象，那么这里举几个例子来感受一下。 首先让我们定义一个对象吧，比如颜色。我们常用 RGB 三个原色">
  <meta property="og:locale" content="zh_CN">
  <meta property="article:published_time" content="2019-06-18T09:21:02.000Z">
  <meta property="article:modified_time" content="2021-12-18T13:11:11.537Z">
  <meta property="article:author" content="崔庆才">
  <meta property="article:tag" content="崔庆才">
  <meta property="article:tag" content="静觅">
  <meta property="article:tag" content="PHP">
  <meta property="article:tag" content="Java">
  <meta property="article:tag" content="Python">
  <meta property="article:tag" content="Spider">
  <meta property="article:tag" content="爬虫">
  <meta property="article:tag" content="Web">
  <meta property="article:tag" content="Kubernetes">
  <meta property="article:tag" content="深度学习">
  <meta property="article:tag" content="机器学习">
  <meta property="article:tag" content="数据分析">
  <meta property="article:tag" content="网络">
  <meta property="article:tag" content="IT">
  <meta property="article:tag" content="技术">
  <meta property="article:tag" content="博客">
  <meta name="twitter:card" content="summary">
  <link rel="canonical" href="https://cuiqingcai.com/6552.html">
  <script id="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };

  </script>
  <title>Python 使用 attrs 和 cattrs 实现面向对象编程 | 静觅</title>
  <meta name="google-site-verification" content="p_bIcnvirkFzG2dYKuNDivKD8-STet5W7D-01woA2fc" />
  <noscript>
    <style>
      .use-motion .brand,
      .use-motion .menu-item,
      .sidebar-inner,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header
      {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle
      {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line-before i
      {
        left: initial;
      }

      .use-motion .logo-line-after i
      {
        right: initial;
      }

    </style>
  </noscript>
  <link rel="alternate" href="/atom.xml" title="静觅" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏">
              <span class="toggle-line toggle-line-first"></span>
              <span class="toggle-line toggle-line-middle"></span>
              <span class="toggle-line toggle-line-last"></span>
            </div>
          </div>
          <div class="site-meta">
            <a href="/" class="brand" rel="start">
              <span class="logo-line-before"><i></i></span>
              <h1 class="site-title">静觅 <span class="site-subtitle"> 崔庆才的个人站点 </span>
              </h1>
              <span class="logo-line-after"><i></i></span>
            </a>
          </div>
          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>
        <nav class="site-nav">
          <ul id="menu" class="main-menu menu">
            <li class="menu-item menu-item-home">
              <a href="/" rel="section">首页</a>
            </li>
            <li class="menu-item menu-item-archives">
              <a href="/archives/" rel="section">文章列表</a>
            </li>
            <li class="menu-item menu-item-tags">
              <a href="/tags/" rel="section">文章标签</a>
            </li>
            <li class="menu-item menu-item-categories">
              <a href="/categories/" rel="section">文章分类</a>
            </li>
            <li class="menu-item menu-item-about">
              <a href="/about/" rel="section">关于博主</a>
            </li>
            <li class="menu-item menu-item-message">
              <a href="/message/" rel="section">给我留言</a>
            </li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger">搜索 </a>
            </li>
          </ul>
        </nav>
        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div id="search-result">
              <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
    </header>
    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>
    <div class="reading-progress-bar"></div>
    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div class="content post posts-expand">
            <article itemscope itemtype="http://schema.org/Article" class="post-block single" lang="zh-CN">
              <link itemprop="mainEntityOfPage" href="https://cuiqingcai.com/6552.html">
              <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
                <meta itemprop="image" content="/images/avatar.png">
                <meta itemprop="name" content="崔庆才">
                <meta itemprop="description" content="崔庆才的个人站点，记录生活的瞬间，分享学习的心得。">
              </span>
              <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
                <meta itemprop="name" content="静觅">
              </span>
              <header class="post-header">
                <h1 class="post-title" itemprop="name headline"> Python 使用 attrs 和 cattrs 实现面向对象编程 </h1>
                <div class="post-meta">
                  <span class="post-meta-item">
                    <span class="post-meta-item-icon">
                      <i class="far fa-user"></i>
                    </span>
                    <span class="post-meta-item-text">作者</span>
                    <span><a href="/authors/崔庆才" class="author" itemprop="url" rel="index">崔庆才</a></span>
                  </span>
                  <span class="post-meta-item">
                    <span class="post-meta-item-icon">
                      <i class="far fa-calendar"></i>
                    </span>
                    <span class="post-meta-item-text">发表于</span>
                    <time title="创建时间：2019-06-18 17:21:02" itemprop="dateCreated datePublished" datetime="2019-06-18T17:21:02+08:00">2019-06-18</time>
                  </span>
                  <span class="post-meta-item">
                    <span class="post-meta-item-icon">
                      <i class="far fa-folder"></i>
                    </span>
                    <span class="post-meta-item-text">分类于</span>
                    <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                      <a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                    </span>
                  </span>
                  <span id="/6552.html" class="post-meta-item leancloud_visitors" data-flag-title="Python 使用 attrs 和 cattrs 实现面向对象编程" title="阅读次数">
                    <span class="post-meta-item-icon">
                      <i class="fa fa-eye"></i>
                    </span>
                    <span class="post-meta-item-text">阅读次数：</span>
                    <span class="leancloud-visitors-count"></span>
                  </span>
                  <span class="post-meta-item" title="本文字数">
                    <span class="post-meta-item-icon">
                      <i class="far fa-file-word"></i>
                    </span>
                    <span class="post-meta-item-text">本文字数：</span>
                    <span>18k</span>
                  </span>
                  <span class="post-meta-item" title="阅读时长">
                    <span class="post-meta-item-icon">
                      <i class="far fa-clock"></i>
                    </span>
                    <span class="post-meta-item-text">阅读时长 &asymp;</span>
                    <span>16 分钟</span>
                  </span>
                </div>
              </header>
              <div class="post-body" itemprop="articleBody">
                <div class="advertisements">
                  <div class="item">
                    <a href="http://i0k.cn/4UUsd" target="_blank">
                      <img src="https://qiniu.cuiqingcai.com/dsdhf.jpg">
                    </a>
                  </div>
                </div>
                <p>Python 是支持面向对象的，很多情况下使用面向对象编程会使得代码更加容易扩展，并且可维护性更高，但是如果你写的多了或者某一对象非常复杂了，其中的一些写法会相当相当繁琐，而且我们会经常碰到对象和 JSON 序列化及反序列化的问题，原生的 Python 转起来还是很费劲的。 可能这么说大家会觉得有点抽象，那么这里举几个例子来感受一下。 首先让我们定义一个对象吧，比如颜色。我们常用 RGB 三个原色来表示颜色，R、G、B 分别代表红、绿、蓝三个颜色的数值，范围是 0-255，也就是每个原色有 256 个取值。如 RGB(0, 0, 0) 就代表黑色，RGB(255, 255, 255) 就代表白色，RGB(255, 0, 0) 就代表红色，如果不太明白可以具体看看 RGB 颜色的定义哈。 好，那么我们现在如果想定义一个颜色对象，那么正常的写法就是这样了，创建这个对象的时候需要三个参数，就是 R、G、B 三个数值，定义如下：</p>
                <figure class="highlight python">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Color</span><span class="params">(object)</span>:</span></span><br><span class="line">    <span class="string">"""</span></span><br><span class="line"><span class="string">    Color Object of RGB</span></span><br><span class="line"><span class="string">    """</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(self, r, g, b)</span>:</span></span><br><span class="line">        self.r = r</span><br><span class="line">        self.g = g</span><br><span class="line">        self.b = b</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>其实对象一般就是这么定义的，初始化方法里面传入各个参数，然后定义全局变量并赋值这些值。其实挺多常用语言比如 Java、PHP 里面都是这么定义的。但其实这种写法是比较冗余的，比如 r、g、b 这三个变量一写就写了三遍。 好，那么我们初始化一下这个对象，然后打印输出下，看看什么结果：</p>
                <figure class="highlight dos">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="built_in">color</span> = <span class="built_in">Color</span>(<span class="number">255</span>, <span class="number">255</span>, <span class="number">255</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="built_in">color</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>结果是什么样的呢？或许我们也就能看懂一个 Color 吧，别的都没有什么有效信息，像这样子：</p>
                <figure class="highlight dos">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">&lt;__main__.<span class="built_in">Color</span> object <span class="built_in">at</span> <span class="number">0</span>x103436f60&gt;</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>我们知道，在 Python 里面想要定义某个对象本身的打印输出结果的时候，需要实现它的 <code>__repr__</code> 方法，所以我们比如我们添加这么一个方法：</p>
                <figure class="highlight python">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">__repr__</span><span class="params">(self)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">f'<span class="subst">&#123;self.__class__.__name__&#125;</span>(r=<span class="subst">&#123;self.r&#125;</span>, g=<span class="subst">&#123;self.g&#125;</span>, b=<span class="subst">&#123;self.b&#125;</span>)'</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里使用了 Python 中的 fstring 来实现了 <code>__repr__</code> 方法，在这里我们构造了一个字符串并返回，字符串中包含了这个 Color 类中的 r、g、b 属性，这个返回的结果就是 print 的打印结果，我们再重新执行一下，结果就变成这样子了：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Color(<span class="attribute">r</span>=255, <span class="attribute">g</span>=255, <span class="attribute">b</span>=255)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>改完之后，这样打印的对象就会变成这样的字符串形式了，感觉看起来清楚多了吧？ 再继续，如果我们要想实现这个对象里面的 <code>__eq__</code>、<code>__lt__</code> 等各种方法来实现对象之间的比较呢？照样需要继续定义成类似这样子的形式：</p>
                <figure class="highlight gml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">def __lt__(<span class="literal">self</span>, <span class="literal">other</span>):</span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> isinstance(<span class="literal">other</span>, <span class="literal">self</span>.__class__): <span class="keyword">return</span> NotImplemented</span><br><span class="line">    <span class="keyword">return</span> (<span class="literal">self</span>.r, <span class="literal">self</span>.g, <span class="literal">self</span>.b) &lt; (<span class="literal">other</span>.r, <span class="literal">other</span>.g, <span class="literal">other</span>.b)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里是 <code>__lt__</code> 方法，有了这个方法就可以使用比较符来对两个 Color 对象进行比较了，但这里又把这几个属性写了两遍。 最后再考虑考虑，如果我要把 JSON 转成 Color 对象，难道我要读完 JSON 然后一个个属性赋值吗？如果我想把 Color 对象转化为 JSON，又得把这几个属性写几遍呢？如果我突然又加了一个属性比如透明度 a 参数，那么整个类的方法和参数都要修改，这是极其难以扩展的。不知道你能不能忍，反正我不能忍！ 如果你用过 Scrapy、Django 等框架，你会发现 Scrapy 里面有一个 Item 的定义，只需要定义一些 Field 就可以了，Django 里面的 Model 也类似这样，只需要定义其中的几个字段属性就可以完成整个类的定义了，非常方便。 说到这里，我们能不能把 Scrapy 或 Django 里面的定义模式直接拿过来呢？能是能，但是没必要，因为我们还有专门为 Python 面向对象而专门诞生的库，没错，就是 attrs 和 cattrs 这两个库。 有了 attrs 库，我们就可以非常方便地定义各个对象了，另外对于 JSON 的转化，可以进一步借助 cattrs 这个库，非常有帮助。 说了这么多，还是没有介绍这两个库的具体用法，下面我们来详细介绍下。</p>
                <h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2>
                <p>安装这两个库非常简单，使用 pip 就好了，命令如下：</p>
                <figure class="highlight cmake">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">pip3 <span class="keyword">install</span> attrs cattrs</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>安装好了之后我们就可以导入并使用这两个库了。</p>
                <h2 id="简介与特性"><a href="#简介与特性" class="headerlink" title="简介与特性"></a>简介与特性</h2>
                <p>首先我们来介绍下 attrs 这个库，其官方的介绍如下：</p>
                <blockquote>
                  <p>attrs 是这样的一个 Python 工具包，它能将你从繁综复杂的实现上解脱出来，享受编写 Python 类的快乐。它的目标就是在不减慢你编程速度的前提下，帮助你来编写简洁而又正确的代码。</p>
                </blockquote>
                <p>其实意思就是用了它，定义和实现 Python 类变得更加简洁和高效。</p>
                <h2 id="基本用法"><a href="#基本用法" class="headerlink" title="基本用法"></a>基本用法</h2>
                <p>首先明确一点，我们现在是装了 attrs 和 cattrs 这两个库，但是实际导入的时候是使用 attr 和 cattr 这两个包，是不带 s 的。 在 attr 这个库里面有两个比较常用的组件叫做 attrs 和 attr，前者是主要用来修饰一个自定义类的，后者是定义类里面的一个字段的。有了它们，我们就可以将上文中的定义改写成下面的样子：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Color</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">r</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">g</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">b</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">color</span> = <span class="symbol">Color</span>(<span class="symbol">255, <span class="symbol">255</span>, <span class="symbol">255</span></span>)</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">color</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>看我们操作的，首先我们导入了刚才所说的两个组件，然后用 attrs 里面修饰了 Color 这个自定义类，然后用 attrib 来定义一个个属性，同时可以指定属性的类型和默认值。最后打印输出，结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Color(<span class="attribute">r</span>=255, <span class="attribute">g</span>=255, <span class="attribute">b</span>=255)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>怎么样，达成了一样的输出效果！ 观察一下有什么变化，是不是变得更简洁了？r、g、b 三个属性都只写了一次，同时还指定了各个字段的类型和默认值，另外也不需要再定义 <code>__init__</code> 方法和 <code>__repr__</code> 方法了，一切都显得那么简洁。一个字，爽！ 实际上，主要是 attrs 这个修饰符起了作用，然后根据定义的 attrib 属性自动帮我们实现了 <code>__init__</code>、<code>__repr__</code>、<code>__eq__</code>、<code>__ne__</code>、<code>__lt__</code>、<code>__le__</code>、<code>__gt__</code>、<code>__ge__</code>、<code>__hash__</code> 这几个方法。 如使用 attrs 修饰的类定义是这样子：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">SmartClass</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">a</span> = <span class="symbol">attrib</span>()</span><br><span class="line">    <span class="symbol">b</span> = <span class="symbol">attrib</span>()</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>其实就相当于已经实现了这些方法：</p>
                <figure class="highlight ruby">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">RoughClass</span>(<span class="title">object</span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span><span class="params">(<span class="keyword">self</span>, a, b)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">self</span>.a = a</span><br><span class="line">        <span class="keyword">self</span>.b = b</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__repr__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">return</span> <span class="string">"RoughClass(a=&#123;&#125;, b=&#123;&#125;)"</span>.format(<span class="keyword">self</span>.a, <span class="keyword">self</span>.b)</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__eq__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">if</span> other.__class_<span class="number">_</span> is <span class="keyword">self</span>.<span class="symbol">__class__:</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">self</span>.a, <span class="keyword">self</span>.b) == (other.a, other.b)</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__ne__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        result = <span class="keyword">self</span>.__eq_<span class="number">_</span>(other)</span><br><span class="line">        <span class="keyword">if</span> result is <span class="symbol">NotImplemented:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">not</span> result</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__lt__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">if</span> other.__class_<span class="number">_</span> is <span class="keyword">self</span>.<span class="symbol">__class__:</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">self</span>.a, <span class="keyword">self</span>.b) &lt; (other.a, other.b)</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__le__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">if</span> other.__class_<span class="number">_</span> is <span class="keyword">self</span>.<span class="symbol">__class__:</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">self</span>.a, <span class="keyword">self</span>.b) &lt;= (other.a, other.b)</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__gt__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">if</span> other.__class_<span class="number">_</span> is <span class="keyword">self</span>.<span class="symbol">__class__:</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">self</span>.a, <span class="keyword">self</span>.b) &gt; (other.a, other.b)</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__ge__</span><span class="params">(<span class="keyword">self</span>, other)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">if</span> other.__class_<span class="number">_</span> is <span class="keyword">self</span>.<span class="symbol">__class__:</span></span><br><span class="line">            <span class="keyword">return</span> (<span class="keyword">self</span>.a, <span class="keyword">self</span>.b) &gt;= (other.a, other.b)</span><br><span class="line">        <span class="symbol">else:</span></span><br><span class="line">            <span class="keyword">return</span> NotImplemented</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__hash__</span><span class="params">(<span class="keyword">self</span>)</span></span><span class="symbol">:</span></span><br><span class="line">        <span class="keyword">return</span> hash((<span class="keyword">self</span>.__class_<span class="number">_</span>, <span class="keyword">self</span>.a, <span class="keyword">self</span>.b))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>所以说，如果我们用了 attrs 的话，就可以不用再写这些冗余又复杂的代码了。 翻看源码可以发现，其内部新建了一个 ClassBuilder，通过一些属性操作来动态添加了上面的这些方法，如果想深入研究，建议可以看下 attrs 库的源码。</p>
                <h2 id="别名使用"><a href="#别名使用" class="headerlink" title="别名使用"></a>别名使用</h2>
                <p>这时候大家可能有个小小的疑问，感觉里面的定义好乱啊，库名叫做 attrs，包名叫做 attr，然后又导入了 attrs 和 attrib，这太奇怪了。为了帮大家解除疑虑，我们来梳理一下它们的名字。 首先库的名字就叫做 attrs，这个就是装 Python 包的时候这么装就行了。但是库的名字和导入的包的名字确实是不一样的，我们用的时候就导入 attr 这个包就行了，里面包含了各种各样的模块和组件，这是完全固定的。 好，然后接下来看看 attr 包里面包含了什么，刚才我们引入了 attrs 和 attrib。 首先是 attrs，它主要是用来修饰 class 类的，而 attrib 主要是用来做属性定义的，这个就记住它们两个的用法就好了。 翻了一下源代码，发现其实它还有一些别名：</p>
                <figure class="highlight ini">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">s</span> = attributes = attrs</span><br><span class="line"><span class="attr">ib</span> = attr = attrib</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>也就是说，attrs 可以用 s 或 attributes 来代替，attrib 可以用 attr 或 ib 来代替。 既然是别名，那么上面的类就可以改写成下面的样子：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> s, ib</span><br><span class="line"></span><br><span class="line">@s</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Color</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">r</span> = <span class="symbol">ib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">g</span> = <span class="symbol">ib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">b</span> = <span class="symbol">ib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">color</span> = <span class="symbol">Color</span>(<span class="symbol">255, <span class="symbol">255</span>, <span class="symbol">255</span></span>)</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">color</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>是不是更加简洁了，当然你也可以把 s 改写为 attributes，ib 改写为 attr，随你怎么用啦。 不过我觉得比较舒服的是 attrs 和 attrib 的搭配，感觉可读性更好一些，当然这个看个人喜好。 所以总结一下：</p>
                <ul>
                  <li>库名：attrs</li>
                  <li>导入包名：attr</li>
                  <li>修饰类：s 或 attributes 或 attrs</li>
                  <li>定义属性：ib 或 attr 或 attrib</li>
                </ul>
                <p>OK，理清了这几部分内容，我们继续往下深入了解它的用法吧。</p>
                <h2 id="声明和比较"><a href="#声明和比较" class="headerlink" title="声明和比较"></a>声明和比较</h2>
                <p>在这里我们再声明一个简单一点的数据结构，比如叫做 Point，包含 x、y 的坐标，定义如下：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>()</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>()</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>其中 attrib 里面什么参数都没有，如果我们要使用的话，参数可以顺次指定，也可以根据名字指定，如：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">p1 = Point(1, 2)</span><br><span class="line"><span class="builtin-name">print</span>(p1)</span><br><span class="line">p2 = Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=2)</span><br><span class="line"><span class="builtin-name">print</span>(p2)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>其效果都是一样的，打印输出结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=2)</span><br><span class="line">Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=2)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>OK，接下来让我们再验证下类之间的比较方法，由于使用了 attrs，相当于我们定义的类已经有了 <code>__eq__</code>、<code>__ne__</code>、<code>__lt__</code>、<code>__le__</code>、<code>__gt__</code>、<code>__ge__</code> 这几个方法，所以我们可以直接使用比较符来对类和类之间进行比较，下面我们用实例来感受一下：</p>
                <figure class="highlight lisp">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">print('Equal:', Point(<span class="number">1</span>, <span class="number">2</span>) == Point(<span class="number">1</span>, <span class="number">2</span>))</span><br><span class="line">print('Not Equal(<span class="name">ne</span>):', Point(<span class="number">1</span>, <span class="number">2</span>) != Point(<span class="number">3</span>, <span class="number">4</span>))</span><br><span class="line">print('Less Than(<span class="name">lt</span>):', Point(<span class="number">1</span>, <span class="number">2</span>) &lt; Point(<span class="number">3</span>, <span class="number">4</span>))</span><br><span class="line">print('Less or Equal(<span class="name">le</span>):', Point(<span class="number">1</span>, <span class="number">2</span>) &lt;= Point(<span class="number">1</span>, <span class="number">4</span>), Point(<span class="number">1</span>, <span class="number">2</span>) &lt;= Point(<span class="number">1</span>, <span class="number">2</span>))</span><br><span class="line">print('Greater Than(<span class="name">gt</span>):', Point(<span class="number">4</span>, <span class="number">2</span>) &gt; Point(<span class="number">3</span>, <span class="number">2</span>), Point(<span class="number">4</span>, <span class="number">2</span>) &gt; Point(<span class="number">3</span>, <span class="number">1</span>))</span><br><span class="line">print('Greater or Equal(<span class="name">ge</span>):', Point(<span class="number">4</span>, <span class="number">2</span>) &gt;= Point(<span class="number">4</span>, <span class="number">1</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>运行结果如下：</p>
                <figure class="highlight yaml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">Same:</span> <span class="literal">False</span></span><br><span class="line"><span class="attr">Equal:</span> <span class="literal">True</span></span><br><span class="line"><span class="string">Not</span> <span class="string">Equal(ne):</span> <span class="literal">True</span></span><br><span class="line"><span class="string">Less</span> <span class="string">Than(lt):</span> <span class="literal">True</span></span><br><span class="line"><span class="string">Less</span> <span class="string">or</span> <span class="string">Equal(le):</span> <span class="literal">True</span> <span class="literal">True</span></span><br><span class="line"><span class="string">Greater</span> <span class="string">Than(gt):</span> <span class="literal">True</span> <span class="literal">True</span></span><br><span class="line"><span class="string">Greater</span> <span class="string">or</span> <span class="string">Equal(ge):</span> <span class="literal">True</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>可能有的朋友不知道 ne、lt、le 什么的是什么意思，不过看到这里你应该明白啦，ne 就是 Not Equal 的意思，就是不相等，le 就是 Less or Equal 的意思，就是小于或等于。 其内部怎么实现的呢，就是把类的各个属性转成元组来比较了，比如 <code>Point(1, 2) &lt; Point(3, 4)</code> 实际上就是比较了 <code>(1, 2)</code> 和 <code>(3, 4)</code> 两个元组，那么元组之间的比较逻辑又是怎样的呢，这里就不展开了，如果不明白的话可以参考官方文档：<a href="https://docs.python.org/3/library/stdtypes.html#comparisons" target="_blank" rel="noopener">https://docs.python.org/3/library/stdtypes.html#comparisons</a>。</p>
                <h2 id="属性定义"><a href="#属性定义" class="headerlink" title="属性定义"></a>属性定义</h2>
                <p>现在看来，对于这个类的定义莫过于每个属性的定义了，也就是 attrib 的定义。对于 attrib 的定义，我们可以传入各种参数，不同的参数对于这个类的定义有非常大的影响。 下面我们就来详细了解一下每个属性的具体参数和用法吧。 首先让我们概览一下总共可能有多少可以控制一个属性的参数，我们用 attrs 里面的 fields 方法可以查看一下：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib, fields</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>()</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>()</span><br><span class="line"></span><br><span class="line"><span class="symbol">print</span>(<span class="symbol">fields</span>(<span class="symbol">Point</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这就可以输出 Point 的所有属性和对应的参数，结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">(Attribute(<span class="attribute">name</span>=<span class="string">'x'</span>, <span class="attribute">default</span>=<span class="literal">NOTHING</span>, <span class="attribute">validator</span>=None, <span class="attribute">repr</span>=<span class="literal">True</span>, <span class="attribute">cmp</span>=<span class="literal">True</span>, <span class="attribute">hash</span>=None, <span class="attribute">init</span>=<span class="literal">True</span>, <span class="attribute">metadata</span>=mappingproxy(&#123;&#125;), <span class="attribute">type</span>=None, <span class="attribute">converter</span>=None, <span class="attribute">kw_only</span>=<span class="literal">False</span>), Attribute(<span class="attribute">name</span>=<span class="string">'y'</span>, <span class="attribute">default</span>=<span class="literal">NOTHING</span>, <span class="attribute">validator</span>=None, <span class="attribute">repr</span>=<span class="literal">True</span>, <span class="attribute">cmp</span>=<span class="literal">True</span>, <span class="attribute">hash</span>=None, <span class="attribute">init</span>=<span class="literal">True</span>, <span class="attribute">metadata</span>=mappingproxy(&#123;&#125;), <span class="attribute">type</span>=None, <span class="attribute">converter</span>=None, <span class="attribute">kw_only</span>=<span class="literal">False</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>输出出来了，可以看到结果是一个元组，元组每一个元素都其实是一个 Attribute 对象，包含了各个参数，下面详细解释下几个参数的含义：</p>
                <ul>
                  <li>name：属性的名字，是一个字符串类型。</li>
                  <li>default：属性的默认值，如果没有传入初始化数据，那么就会使用默认值。如果没有默认值定义，那么就是 NOTHING，即没有默认值。</li>
                  <li>validator：验证器，检查传入的参数是否合法。</li>
                  <li>init：是否参与初始化，如果为 False，那么这个参数不能当做类的初始化参数，默认是 True。</li>
                  <li>metadata：元数据，只读性的附加数据。</li>
                  <li>type：类型，比如 int、str 等各种类型，默认为 None。</li>
                  <li>converter：转换器，进行一些值的处理和转换器，增加容错性。</li>
                  <li>kw_only：是否为强制关键字参数，默认为 False。</li>
                </ul>
                <h3 id="属性名"><a href="#属性名" class="headerlink" title="属性名"></a>属性名</h3>
                <p>对于属性名，非常清楚了，我们定义什么属性，属性名就是什么，例如上面的例子，定义了：</p>
                <figure class="highlight ini">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">x</span> = attrib()</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>那么其属性名就是 x。</p>
                <h3 id="默认值"><a href="#默认值" class="headerlink" title="默认值"></a>默认值</h3>
                <p>对于默认值，如果在初始化的时候没有指定，那么就会默认使用默认值进行初始化，我们看下面的一个实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib, fields</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>()</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">default</span>=<span class="symbol">100</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>(<span class="symbol">x</span>=<span class="symbol">1, <span class="symbol">y</span></span>=<span class="symbol">3</span>))</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>(<span class="symbol">x</span>=<span class="symbol">1</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里我们将 y 属性的默认值设置为了 100，在初始化的时候，第一次都传入了 x、y 两个参数，第二次只传入了 x 这个参数，看下运行结果：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=3)</span><br><span class="line">Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=100)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>可以看到结果，当设置了默认参数的属性没有被传入值时，他就会使用设置的默认值进行初始化。 那假如没有设置默认值但是也没有初始化呢？比如执行下：</p>
                <figure class="highlight stylus">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="function"><span class="title">Point</span><span class="params">()</span></span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>那么就会报错了，错误如下：</p>
                <figure class="highlight groovy">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="string">TypeError:</span> __init__() missing <span class="number">1</span> required positional <span class="string">argument:</span> <span class="string">'x'</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>所以说，如果一个属性，我们一旦没有设置默认值同时没有传入的话，就会引起错误。所以，一般来说，为了稳妥起见，设置一个默认值比较好，即使是 None 也可以的。</p>
                <h3 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h3>
                <p>如果一个类的某些属性不想参与初始化，比如想直接设置一个初始值，一直固定不变，我们可以将属性的 init 参数设置为 False，看一个实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">init</span>=<span class="symbol">False, <span class="symbol">default</span></span>=<span class="symbol">10</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>()</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>(<span class="symbol">3</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>比如 x 我们只想在初始化的时候设置固定值，不想初始化的时候被改变和设定，我们将其设置了 init 参数为 False，同时设置了一个默认值，如果不设置默认值，默认为 NOTHING。然后初始化的时候我们只传入了一个值，其实也就是为 y 这个属性赋值。 这样的话，看下运行结果：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=10, <span class="attribute">y</span>=3)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>没什么问题，y 被赋值为了我们设置的值 3。 那假如我们非要设置 x 呢？会发生什么，比如改写成这样子：</p>
                <figure class="highlight stylus">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="function"><span class="title">Point</span><span class="params">(<span class="number">1</span>, <span class="number">2</span>)</span></span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>报错了，错误如下：</p>
                <figure class="highlight yaml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">TypeError:</span> <span class="string">__init__()</span> <span class="string">takes</span> <span class="number">2</span> <span class="string">positional</span> <span class="string">arguments</span> <span class="string">but</span> <span class="number">3</span> <span class="string">were</span> <span class="string">given</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>参数过多，也就是说，已经将 init 设置为 False 的属性就不再被算作可以被初始化的属性了。</p>
                <h3 id="强制关键字"><a href="#强制关键字" class="headerlink" title="强制关键字"></a>强制关键字</h3>
                <p>强制关键字是 Python 里面的一个特性，在传入的时候必须使用关键字的名字来传入，如果不太理解可以再了解下 Python 的基础。 设置了强制关键字参数的属性必须要放在后面，其后面不能再有非强制关键字参数的属性，否则会报这样的错误：</p>
                <figure class="highlight pgsql">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">ValueError: Non keyword-<span class="keyword">only</span> attributes are <span class="keyword">not</span> allowed <span class="keyword">after</span> a keyword-<span class="keyword">only</span> <span class="keyword">attribute</span> (unless they are init=<span class="keyword">False</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>好，我们来看一个例子，我们将最后一个属性设置 kw_only 参数为 True：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib, fields</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">default</span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">kw_only</span>=<span class="symbol">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>(<span class="symbol">1, <span class="symbol">y</span></span>=<span class="symbol">3</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>如果设置了 kw_only 参数为 True，那么在初始化的时候必须传入关键字的名字，这里就必须指定 y 这个名字，运行结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=3)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>如果没有指定 y 这个名字，像这样调用：</p>
                <figure class="highlight stylus">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="function"><span class="title">Point</span><span class="params">(<span class="number">1</span>, <span class="number">3</span>)</span></span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>那么就会报错：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">TypeError: __init__() takes <span class="keyword">from</span> <span class="number">1</span> to <span class="number">2</span> positional arguments but <span class="number">3</span> were given</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>所以，这个参数就是设置初始化传参必须要用名字来传，否则会出现错误。 注意，如果我们将一个属性设置了 init 为 False，那么 kw_only 这个参数会被忽略。</p>
                <h3 id="验证器"><a href="#验证器" class="headerlink" title="验证器"></a>验证器</h3>
                <p>有时候在设置一个属性的时候必须要满足某个条件，比如性别必须要是男或者女，否则就不合法。对于这种情况，我们就需要有条件来控制某些属性不能为非法值。 下面我们看一个实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">def is_valid_gender(instance, attribute, value):</span><br><span class="line">    <span class="keyword">if</span> value <span class="keyword">not</span> <span class="keyword">in</span> [<span class="string">'male'</span>, <span class="string">'female'</span>]:</span><br><span class="line">        raise ValueError(f<span class="string">'gender &#123;value&#125; is not valid'</span>)</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Person</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">name</span> = <span class="symbol">attrib</span>()</span><br><span class="line">    <span class="symbol">gender</span> = <span class="symbol">attrib</span>(<span class="symbol">validator</span>=<span class="symbol">is_valid_gender</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Person</span>(<span class="symbol">name</span>='<span class="symbol">Mike</span>', <span class="symbol">gender</span>='<span class="symbol">male</span>'))</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Person</span>(<span class="symbol">name</span>='<span class="symbol">Mike</span>', <span class="symbol">gender</span>='<span class="symbol">mlae</span>'))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里我们定义了一个验证器 Validator 方法，叫做 is_valid_gender。然后定义了一个类 Person 还有它的两个属性 name 和 gender，其中 gender 定义的时候传入了一个参数 validator，其值就是我们定义的 Validator 方法。 这个 Validator 定义的时候有几个固定的参数：</p>
                <ul>
                  <li>instance：类对象</li>
                  <li>attribute：属性名</li>
                  <li>value：属性值</li>
                </ul>
                <p>这是三个参数是固定的，在类初始化的时候，其内部会将这三个参数传递给这个 Validator，因此 Validator 里面就可以接受到这三个值，然后进行判断即可。在 Validator 里面，我们判断如果不是男性或女性，那么就直接抛出错误。 下面做了两个实验，一个就是正常传入 male，另一个写错了，写的是 mlae，观察下运行结果：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Person(<span class="attribute">name</span>=<span class="string">'Mike'</span>, <span class="attribute">gender</span>=<span class="string">'male'</span>)</span><br><span class="line">TypeError: __init__() missing 1 required positional argument: <span class="string">'gender'</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>OK，结果显而易见了，第二个报错了，因为其值不是正常的性别，所以程序直接报错终止。 注意在 Validator 里面返回 True 或 False 是没用的，错误的值还会被照常复制。所以，一定要在 Validator 里面 raise 某个错误。 另外 attrs 库里面还给我们内置了好多 Validator，比如判断类型，这里我们再增加一个属性 age，必须为 int 类型：</p>
                <figure class="highlight lisp">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">age = attrib(<span class="name">validator=validators</span>.instance_of(<span class="name">int</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这时候初始化的时候就必须传入 int 类型，如果为其他类型，则直接抛错：</p>
                <figure class="highlight less">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attribute">TypeError</span>: ("<span class="string">'age'</span> must be &lt;class <span class="string">'int'</span>&gt; (got <span class="string">'x'</span> that is a &lt;class <span class="string">'str'</span>&gt;).</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>另外还有其他的一些 Validator，比如与或运算、可执行判断、可迭代判断等等，可以参考官方文档：<a href="https://www.attrs.org/en/stable/api.html#validators" target="_blank" rel="noopener">https://www.attrs.org/en/stable/api.html#validators</a>。 另外 validator 参数还支持多个 Validator，比如我们要设置既要是数字，又要小于 100，那么可以把几个 Validator 放到一个列表里面并传入：</p>
                <figure class="highlight reasonml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">from attr import attrs, attrib, validators</span><br><span class="line"></span><br><span class="line">def is<span class="constructor">_less_than_100(<span class="params">instance</span>, <span class="params">attribute</span>, <span class="params">value</span>)</span>:</span><br><span class="line">    <span class="keyword">if</span> value &gt; <span class="number">100</span>:</span><br><span class="line">        raise <span class="constructor">ValueError(<span class="params">f</span>'<span class="params">age</span> &#123;<span class="params">value</span>&#125; <span class="params">must</span> <span class="params">less</span> <span class="params">than</span> 100')</span></span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="constructor">Person(<span class="params">object</span>)</span>:</span><br><span class="line">    name = attrib<span class="literal">()</span></span><br><span class="line">    gender = attrib(validator=is_valid_gender)</span><br><span class="line">    age = attrib(validator=<span class="literal">[<span class="identifier">validators</span>.<span class="identifier">instance_of</span>(<span class="identifier">int</span>), <span class="identifier">is_less_than_100</span>]</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__<span class="operator"> == </span>'__main__':</span><br><span class="line">    print(<span class="constructor">Person(<span class="params">name</span>='Mike', <span class="params">gender</span>='<span class="params">male</span>', <span class="params">age</span>=500)</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这样就会将所有的 Validator 都执行一遍，必须每个 Validator 都满足才可以。这里 age 传入了 500，那么不符合第二个 Validator，直接抛错：</p>
                <figure class="highlight yaml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">ValueError:</span> <span class="string">age</span> <span class="number">500</span> <span class="string">must</span> <span class="string">less</span> <span class="string">than</span> <span class="number">100</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <h3 id="转换器"><a href="#转换器" class="headerlink" title="转换器"></a>转换器</h3>
                <p>其实很多时候我们会不小心传入一些形式不太标准的结果，比如本来是 int 类型的 100，我们传入了字符串类型的 100，那这时候直接抛错应该不好吧，所以我们可以设置一些转换器来增强容错机制，比如将字符串自动转为数字等等，看一个实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">def to_int(value):</span><br><span class="line">    <span class="keyword">try</span>:</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">int</span>(value)</span><br><span class="line">    except:</span><br><span class="line">        <span class="keyword">return</span> None</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">converter</span>=<span class="symbol">to_int</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>()</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>('<span class="symbol">100</span>', <span class="symbol">3</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>看这里，我们定义了一个方法，可以将值转化为数字类型，如果不能转，那么就返回 None，这样保证了任何可以被转数字的值都被转为数字，否则就留空，容错性非常高。 运行结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=100, <span class="attribute">y</span>=3)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <h3 id="类型"><a href="#类型" class="headerlink" title="类型"></a>类型</h3>
                <p>为什么把这个放到最后来讲呢，因为 Python 中的类型是非常复杂的，有原生类型，有 typing 类型，有自定义类的类型。 首先我们来看看原生类型是怎样的，这个很容易理解了，就是普通的 int、float、str 等类型，其定义如下：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>()</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>(<span class="symbol">100, <span class="symbol">3</span></span>))</span><br><span class="line">    <span class="symbol">print</span>(<span class="symbol">Point</span>('<span class="symbol">100</span>', <span class="symbol">3</span>))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里我们将 x 属性定义为 int 类型了，初始化的时候传入了数值型 100 和字符串型 100，结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Point(<span class="attribute">x</span>=100, <span class="attribute">y</span>=3)</span><br><span class="line">Point(<span class="attribute">x</span>=<span class="string">'100'</span>, <span class="attribute">y</span>=3)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>但我们发现，虽然定义了，但是不会被自动转类型的。 另外我们还可以自定义 typing 里面的类型，比如 List，另外 attrs 里面也提供了类型的定义：</p>
                <figure class="highlight elm">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="title">from</span> attr <span class="keyword">import</span> attrs, attrib, Factory</span><br><span class="line"><span class="keyword">import</span> typing</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="title">class</span> <span class="type">Point</span>(object):</span><br><span class="line">    x = attrib(<span class="keyword">type</span>=int)</span><br><span class="line">    y = attrib(<span class="keyword">type</span>=typing.<span class="type">List</span>[int])</span><br><span class="line">    z = attrib(<span class="keyword">type</span>=<span class="type">Factory</span>(list))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里我们引入了 typing 这个包，定义了 y 为 int 数字组成的列表，z 使用了 attrs 里面定义的 Factory 定义了同样为列表类型。 另外我们也可以进行类型的嵌套，比如像这样子：</p>
                <figure class="highlight pgsql">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib, Factory</span><br><span class="line"><span class="keyword">import</span> typing</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="type">Point</span>(<span class="keyword">object</span>):</span><br><span class="line">    x = attrib(<span class="keyword">type</span>=<span class="type">int</span>, default=<span class="number">0</span>)</span><br><span class="line">    y = attrib(<span class="keyword">type</span>=<span class="type">int</span>, default=<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> Line(<span class="keyword">object</span>):</span><br><span class="line">    <span class="type">name</span> = attrib()</span><br><span class="line">    points = attrib(<span class="keyword">type</span>=typing.List[<span class="type">Point</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</span><br><span class="line">    points = [<span class="type">Point</span>(i, i) <span class="keyword">for</span> i <span class="keyword">in</span> range(<span class="number">5</span>)]</span><br><span class="line">    print(points)</span><br><span class="line">    <span class="type">line</span> = Line(<span class="type">name</span>=<span class="string">'line1'</span>, points=points)</span><br><span class="line">    print(<span class="type">line</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里我们定义了 Point 类代表离散点，随后定义了线，其拥有 points 属性是 Point 组成的列表。在初始化的时候我们声明了五个点，然后用这五个点组成的列表声明了一条线，逻辑没什么问题。 运行结果：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">[Point(<span class="attribute">x</span>=0, <span class="attribute">y</span>=0), Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=1), Point(<span class="attribute">x</span>=2, <span class="attribute">y</span>=2), Point(<span class="attribute">x</span>=3, <span class="attribute">y</span>=3), Point(<span class="attribute">x</span>=4, <span class="attribute">y</span>=4)]</span><br><span class="line">Line(<span class="attribute">name</span>=<span class="string">'line1'</span>, points=[Point(<span class="attribute">x</span>=0, <span class="attribute">y</span>=0), Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=1), Point(<span class="attribute">x</span>=2, <span class="attribute">y</span>=2), Point(<span class="attribute">x</span>=3, <span class="attribute">y</span>=3), Point(<span class="attribute">x</span>=4, <span class="attribute">y</span>=4)])</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>可以看到这里我们得到了一个嵌套类型的 Line 对象，其值是 Point 类型组成的列表。 以上便是一些属性的定义，把握好这些属性的定义，我们就可以非常方便地定义一个类了。</p>
                <h2 id="序列转换"><a href="#序列转换" class="headerlink" title="序列转换"></a>序列转换</h2>
                <p>在很多情况下，我们经常会遇到 JSON 等字符串序列和对象互相转换的需求，尤其是在写 REST API、数据库交互的时候。 attrs 库的存在让我们可以非常方便地定义 Python 类，但是它对于序列字符串的转换功能还是比较薄弱的，cattrs 这个库就是用来弥补这个缺陷的，下面我们再来看看 cattrs 这个库。 cattrs 导入的时候名字也不太一样，叫做 cattr，它里面提供了两个主要的方法，叫做 structure 和 unstructure，两个方法是相反的，对于类的序列化和反序列化支持非常好。</p>
                <h3 id="基本转换"><a href="#基本转换" class="headerlink" title="基本转换"></a>基本转换</h3>
                <p>首先我们来看看基本的转换方法的用法，看一个基本的转换实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"><span class="keyword">from</span> cattr <span class="keyword">import</span> unstructure, structure</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">point</span> = <span class="symbol">Point</span>(<span class="symbol">x</span>=<span class="symbol">1, <span class="symbol">y</span></span>=<span class="symbol">2</span>)</span><br><span class="line">    <span class="symbol">json</span> = <span class="symbol">unstructure</span>(<span class="symbol">point</span>)</span><br><span class="line">    <span class="symbol">print</span>('<span class="symbol">json:</span>', <span class="symbol">json</span>)</span><br><span class="line">    <span class="symbol">obj</span> = <span class="symbol">structure</span>(<span class="symbol">json, <span class="symbol">Point</span></span>)</span><br><span class="line">    <span class="symbol">print</span>('<span class="symbol">obj:</span>', <span class="symbol">obj</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里我们定义了一个 Point 对象，然后调用 unstructure 方法即可直接转换为 JSON 字符串。如果我们再想把它转回来，那就需要调用 structure 方法，这样就成功转回了一个 Point 对象。 看下运行结果：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">json: &#123;<span class="string">'x'</span>: 1, <span class="string">'y'</span>: 2&#125;</span><br><span class="line">obj: Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=2)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>当然这种基本的来回转用的多了就轻车熟路了。</p>
                <h3 id="多类型转换"><a href="#多类型转换" class="headerlink" title="多类型转换"></a>多类型转换</h3>
                <p>另外 structure 也支持一些其他的类型转换，看下实例：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">\&gt;&gt;&gt; cattr.structure(<span class="number">1</span>, str)</span><br><span class="line"><span class="string">'1'</span></span><br><span class="line">&gt;&gt;&gt; cattr.structure(<span class="string">"1"</span>, <span class="built_in">float</span>)</span><br><span class="line"><span class="number">1.0</span></span><br><span class="line">&gt;&gt;&gt; cattr.structure([<span class="number">1.0</span>, <span class="number">2</span>, <span class="string">"3"</span>], Tuple[<span class="built_in">int</span>, <span class="built_in">int</span>, <span class="built_in">int</span>])</span><br><span class="line">(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line">&gt;&gt;&gt; cattr.structure((<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>), MutableSequence[<span class="built_in">int</span>])</span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line">&gt;&gt;&gt; cattr.structure((<span class="number">1</span>, None, <span class="number">3</span>), List[Optional[str]])</span><br><span class="line">[<span class="string">'1'</span>, None, <span class="string">'3'</span>]</span><br><span class="line">&gt;&gt;&gt; cattr.structure([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>], Set)</span><br><span class="line">&#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125;</span><br><span class="line">&gt;&gt;&gt; cattr.structure([[<span class="number">1</span>, <span class="number">2</span>], [<span class="number">3</span>, <span class="number">4</span>]], Set[FrozenSet[str]])</span><br><span class="line">&#123;frozenset(&#123;<span class="string">'4'</span>, <span class="string">'3'</span>&#125;), frozenset(&#123;<span class="string">'1'</span>, <span class="string">'2'</span>&#125;)&#125;</span><br><span class="line">&gt;&gt;&gt; cattr.structure(OrderedDict([(<span class="number">1</span>, <span class="number">2</span>), (<span class="number">3</span>, <span class="number">4</span>)]), Dict)</span><br><span class="line">&#123;<span class="number">1</span>: <span class="number">2</span>, <span class="number">3</span>: <span class="number">4</span>&#125;</span><br><span class="line">&gt;&gt;&gt; cattr.structure([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>], Tuple[<span class="built_in">int</span>, str, <span class="built_in">float</span>])</span><br><span class="line">(<span class="number">1</span>, <span class="string">'2'</span>, <span class="number">3.0</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里面用到了 Tuple、MutableSequence、Optional、Set 等类，都属于 typing 这个模块，后面我会写内容详细介绍这个库的用法。 不过总的来说，大部分情况下，JSON 和对象的互转是用的最多的。</p>
                <h3 id="属性处理"><a href="#属性处理" class="headerlink" title="属性处理"></a>属性处理</h3>
                <p>上面的例子都是理想情况下使用的，但在实际情况下，很容易遇到 JSON 和对象不对应的情况，比如 JSON 多个字段，或者对象多个字段。 我们先看看下面的例子：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"><span class="keyword">from</span> cattr <span class="keyword">import</span> structure</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">json</span> = &#123;<span class="string">'x'</span>: <span class="number">1</span>, <span class="string">'y'</span>: <span class="number">2</span>, <span class="string">'z'</span>: <span class="number">3</span>&#125;</span><br><span class="line">print(structure(json, Point))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里，JSON 多了一个字段 z，而 Point 类只有 x、y 两个字段，那么直接执行 structure 会出现什么情况呢？</p>
                <figure class="highlight avrasm">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="symbol">TypeError:</span> __init__() got an unexpected keyword argument <span class="string">'z'</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>不出所料，报错了。意思是多了一个参数，这个参数并没有被定义。 这时候一般的解决方法的直接忽略这个参数，可以重写一下 structure 方法，定义如下：</p>
                <figure class="highlight reasonml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">def drop<span class="constructor">_nonattrs(<span class="params">d</span>, <span class="params">type</span>)</span>:</span><br><span class="line">    <span class="keyword">if</span> not isinstance(d, dict): return d</span><br><span class="line">    attrs_attrs = getattr(<span class="keyword">type</span>, '__attrs_attrs__', None)</span><br><span class="line">    <span class="keyword">if</span> attrs_attrs is None:</span><br><span class="line">        raise <span class="constructor">ValueError(<span class="params">f</span>'<span class="params">type</span> &#123;<span class="params">type</span>&#125; <span class="params">is</span> <span class="params">not</span> <span class="params">an</span> <span class="params">attrs</span> <span class="params">class</span>')</span></span><br><span class="line">    attrs: Set<span class="literal">[<span class="identifier">str</span>]</span> = &#123;attr.name for attr <span class="keyword">in</span> attrs_attrs&#125;</span><br><span class="line">    return &#123;key: <span class="keyword">val</span> for key, <span class="keyword">val</span> <span class="keyword">in</span> d.items<span class="literal">()</span> <span class="keyword">if</span> key <span class="keyword">in</span> attrs&#125;</span><br><span class="line"></span><br><span class="line">def structure(d, <span class="keyword">type</span>):</span><br><span class="line">    return cattr.structure(drop<span class="constructor">_nonattrs(<span class="params">d</span>, <span class="params">type</span>)</span>, <span class="keyword">type</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里定义了一个 drop_nonattrs 方法，用于从 JSON 里面删除对象里面不存在的属性，然后调用新的 structure 方法即可，写法如下：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> Set</span><br><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"><span class="keyword">import</span> cattr</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line"><span class="symbol">def</span> <span class="symbol">drop_nonattrs</span>(<span class="symbol">d, <span class="symbol">type</span></span>):</span><br><span class="line">    <span class="symbol">if</span> <span class="symbol">not</span> <span class="symbol">isinstance</span>(<span class="symbol">d, <span class="symbol">dict</span></span>): <span class="symbol">return</span> <span class="symbol">d</span></span><br><span class="line">    <span class="symbol">attrs_attrs</span> = <span class="symbol">getattr</span>(<span class="symbol">type, </span>'<span class="symbol">__attrs_attrs__</span>', <span class="symbol">None</span>)</span><br><span class="line">    <span class="symbol">if</span> <span class="symbol">attrs_attrs</span> <span class="symbol">is</span> <span class="symbol">None:</span></span><br><span class="line">        <span class="symbol">raise</span> <span class="symbol">ValueError</span>(<span class="symbol">f</span>'<span class="symbol">type</span> &#123;type&#125; <span class="keyword">is</span> <span class="keyword">not</span> an attrs <span class="keyword">class</span>')</span><br><span class="line">    <span class="symbol">attrs: <span class="symbol">Set</span></span>[<span class="symbol">str</span>] = &#123;attr.name <span class="keyword">for</span> attr <span class="keyword">in</span> attrs_attrs&#125;</span><br><span class="line">    <span class="keyword">return</span> &#123;key: val <span class="keyword">for</span> key, val <span class="keyword">in</span> d.items() <span class="keyword">if</span> key <span class="keyword">in</span> attrs&#125;</span><br><span class="line"></span><br><span class="line">def structure(d, type):</span><br><span class="line">    <span class="keyword">return</span> cattr.structure(drop_nonattrs(d, type), type)</span><br><span class="line"></span><br><span class="line">json = &#123;<span class="string">'x'</span>: <span class="number">1</span>, <span class="string">'y'</span>: <span class="number">2</span>, <span class="string">'z'</span>: <span class="number">3</span>&#125;</span><br><span class="line">print(structure(json, Point))</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这样我们就可以避免 JSON 字段冗余导致的转换问题了。 另外还有一个常见的问题，那就是数据对象转换，比如对于时间来说，在对象里面声明我们一般会声明为 datetime 类型，但在序列化的时候却需要序列化为字符串。 所以，对于一些特殊类型的属性，我们往往需要进行特殊处理，这时候就需要我们针对某种特定的类型定义特定的 hook 处理方法，这里就需要用到 register_unstructure_hook 和 register_structure_hook 方法了。 下面这个例子是时间 datetime 转换的时候进行的处理：</p>
                <figure class="highlight haskell">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="title">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"><span class="keyword">import</span> cattr</span><br><span class="line"></span><br><span class="line"><span class="type">TIME_FORMAT</span> = '%<span class="type">Y</span>-%m-%dT%<span class="type">H</span>:%<span class="type">M</span>:%<span class="type">S</span>.%fZ'</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="type">Event</span>(<span class="title">object</span>):</span></span><br><span class="line"><span class="class">    happened_at = attrib(<span class="title">type</span>=<span class="title">datetime</span>.<span class="title">datetime</span>)</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">cattr.register_unstructure_hook(<span class="title">datetime</span>.<span class="title">datetime</span>, <span class="title">lambda</span> <span class="title">dt</span>: <span class="title">dt</span>.<span class="title">strftime</span>(<span class="type">TIME_FORMAT</span>))</span></span><br><span class="line"><span class="class">cattr.register_structure_hook(<span class="title">datetime</span>.<span class="title">datetime</span>,</span></span><br><span class="line"><span class="class">                              <span class="title">lambda</span> <span class="title">string</span>, <span class="title">_</span>: <span class="title">datetime</span>.<span class="title">datetime</span>.<span class="title">strptime</span>(<span class="title">string</span>, <span class="type">TIME_FORMAT</span>))</span></span><br><span class="line"><span class="class"></span></span><br><span class="line"><span class="class">event = <span class="type">Event</span>(<span class="title">happened_at</span>=<span class="title">datetime</span>.<span class="title">datetime</span>(2019, 6, 1))</span></span><br><span class="line"><span class="class">print('<span class="title">event</span>:', <span class="title">event</span>)</span></span><br><span class="line"><span class="class">json = cattr.unstructure(<span class="title">event</span>)</span></span><br><span class="line"><span class="class">print('<span class="title">json</span>:', <span class="title">json</span>)</span></span><br><span class="line"><span class="class">event = cattr.structure(<span class="title">json</span>, <span class="type">Event</span>)</span></span><br><span class="line"><span class="class">print('<span class="type">Event</span>:', <span class="title">event</span>)</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>在这里我们对 datetime 这个类型注册了两个 hook，当序列化的时候，就调用 strftime 方法转回字符串，当反序列化的时候，就调用 strptime 将其转回 datetime 类型。 看下运行结果：</p>
                <figure class="highlight yaml">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="attr">event:</span> <span class="string">Event(happened_at=datetime.datetime(2019,</span> <span class="number">6</span><span class="string">,</span> <span class="number">1</span><span class="string">,</span> <span class="number">0</span><span class="string">,</span> <span class="number">0</span><span class="string">))</span></span><br><span class="line"><span class="attr">json:</span> <span class="string">&#123;'happened_at':</span> <span class="string">'2019-06-01T00:00:00.000000Z'</span><span class="string">&#125;</span></span><br><span class="line"><span class="attr">Event:</span> <span class="string">Event(happened_at=datetime.datetime(2019,</span> <span class="number">6</span><span class="string">,</span> <span class="number">1</span><span class="string">,</span> <span class="number">0</span><span class="string">,</span> <span class="number">0</span><span class="string">))</span></span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这样对于一些特殊类型的属性处理也得心应手了。</p>
                <h3 id="嵌套处理"><a href="#嵌套处理" class="headerlink" title="嵌套处理"></a>嵌套处理</h3>
                <p>最后我们再来看看嵌套类型的处理，比如类里面有个属性是另一个类的类型，如果遇到这种嵌套类的话，怎样类转转换呢？我们用一个实例感受下：</p>
                <figure class="highlight angelscript">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line"><span class="keyword">from</span> attr <span class="keyword">import</span> attrs, attrib</span><br><span class="line"><span class="keyword">from</span> typing <span class="keyword">import</span> List</span><br><span class="line"><span class="keyword">from</span> cattr <span class="keyword">import</span> structure, unstructure</span><br><span class="line"></span><br><span class="line">@attrs</span><br><span class="line"><span class="keyword">class</span> <span class="symbol">Point</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">x</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">y</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">int, <span class="symbol">default</span></span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line">@<span class="symbol">attrs</span></span><br><span class="line"><span class="symbol">class</span> <span class="symbol">Color</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">r</span> = <span class="symbol">attrib</span>(<span class="symbol">default</span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">g</span> = <span class="symbol">attrib</span>(<span class="symbol">default</span>=<span class="symbol">0</span>)</span><br><span class="line">    <span class="symbol">b</span> = <span class="symbol">attrib</span>(<span class="symbol">default</span>=<span class="symbol">0</span>)</span><br><span class="line"></span><br><span class="line">@<span class="symbol">attrs</span></span><br><span class="line"><span class="symbol">class</span> <span class="symbol">Line</span>(<span class="symbol">object</span>):</span><br><span class="line">    <span class="symbol">color</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">Color</span>)</span><br><span class="line">    <span class="symbol">points</span> = <span class="symbol">attrib</span>(<span class="symbol">type</span>=<span class="symbol">List</span>[<span class="symbol">Point</span>])</span><br><span class="line"></span><br><span class="line"><span class="symbol">if</span> <span class="symbol">__name__</span> == '<span class="symbol">__main__</span>':</span><br><span class="line">    <span class="symbol">line</span> = <span class="symbol">Line</span>(<span class="symbol">color</span>=<span class="symbol">Color</span>(), <span class="symbol">points</span>=[<span class="symbol">Point</span>(<span class="symbol">i, <span class="symbol">i</span></span>) <span class="symbol">for</span> <span class="symbol">i</span> <span class="symbol">in</span> <span class="symbol">range</span>(<span class="symbol">5</span>)])</span><br><span class="line">    <span class="symbol">print</span>('<span class="symbol">Object:</span>', <span class="symbol">line</span>)</span><br><span class="line">    <span class="symbol">json</span> = <span class="symbol">unstructure</span>(<span class="symbol">line</span>)</span><br><span class="line">    <span class="symbol">print</span>('<span class="symbol">JSON:</span>', <span class="symbol">json</span>)</span><br><span class="line">    <span class="symbol">line</span> = <span class="symbol">structure</span>(<span class="symbol">json, <span class="symbol">Line</span></span>)</span><br><span class="line">    <span class="symbol">print</span>('<span class="symbol">Object:</span>', <span class="symbol">line</span>)</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>这里我们定义了两个 Class，一个是 Point，一个是 Color，然后定义了 Line 对象，其属性类型一个是 Color 类型，一个是 Point 类型组成的列表，下面我们进行序列化和反序列化操作，转成 JSON 然后再由 JSON 转回来，运行结果如下：</p>
                <figure class="highlight routeros">
                  <table>
                    <tr>
                      <td class="gutter">
                        <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                      </td>
                      <td class="code">
                        <pre><span class="line">Object: Line(<span class="attribute">color</span>=Color(r=0, <span class="attribute">g</span>=0, <span class="attribute">b</span>=0), points=[Point(<span class="attribute">x</span>=0, <span class="attribute">y</span>=0), Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=1), Point(<span class="attribute">x</span>=2, <span class="attribute">y</span>=2), Point(<span class="attribute">x</span>=3, <span class="attribute">y</span>=3), Point(<span class="attribute">x</span>=4, <span class="attribute">y</span>=4)])</span><br><span class="line">JSON: &#123;<span class="string">'color'</span>: &#123;<span class="string">'r'</span>: 0, <span class="string">'g'</span>: 0, <span class="string">'b'</span>: 0&#125;, <span class="string">'points'</span>: [&#123;<span class="string">'x'</span>: 0, <span class="string">'y'</span>: 0&#125;, &#123;<span class="string">'x'</span>: 1, <span class="string">'y'</span>: 1&#125;, &#123;<span class="string">'x'</span>: 2, <span class="string">'y'</span>: 2&#125;, &#123;<span class="string">'x'</span>: 3, <span class="string">'y'</span>: 3&#125;, &#123;<span class="string">'x'</span>: 4, <span class="string">'y'</span>: 4&#125;]&#125;</span><br><span class="line">Object: Line(<span class="attribute">color</span>=Color(r=0, <span class="attribute">g</span>=0, <span class="attribute">b</span>=0), points=[Point(<span class="attribute">x</span>=0, <span class="attribute">y</span>=0), Point(<span class="attribute">x</span>=1, <span class="attribute">y</span>=1), Point(<span class="attribute">x</span>=2, <span class="attribute">y</span>=2), Point(<span class="attribute">x</span>=3, <span class="attribute">y</span>=3), Point(<span class="attribute">x</span>=4, <span class="attribute">y</span>=4)])</span><br></pre>
                      </td>
                    </tr>
                  </table>
                </figure>
                <p>可以看到，我们非常方便地将对象转化为了 JSON 对象，然后也非常方便地转回了对象。 这样我们就成功实现了嵌套对象的序列化和反序列化，所有问题成功解决！</p>
                <h2 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h2>
                <p>本节介绍了利用 attrs 和 cattrs 两个库实现 Python 面向对象编程的实践，有了它们两个的加持，Python 面向对象编程不再是难事。</p>
              </div>
              <div class="reward-container">
                <div></div>
                <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';"> 打赏 </button>
                <div id="qr" style="display: none;">
                  <div style="display: inline-block;">
                    <img src="/images/wechatpay.jpg" alt="崔庆才 微信支付">
                    <p>微信支付</p>
                  </div>
                  <div style="display: inline-block;">
                    <img src="/images/alipay.jpg" alt="崔庆才 支付宝">
                    <p>支付宝</p>
                  </div>
                </div>
              </div>
              <footer class="post-footer">
                <div class="post-nav">
                  <div class="post-nav-item">
                    <a href="/6607.html" rel="prev" title="代码整洁之道-编写 Pythonic 代码">
                      <i class="fa fa-chevron-left"></i> 代码整洁之道-编写 Pythonic 代码 </a>
                  </div>
                  <div class="post-nav-item">
                    <a href="/6613.html" rel="next" title="Python 机器学习算法一之线性回归的推导及实战"> Python 机器学习算法一之线性回归的推导及实战 <i class="fa fa-chevron-right"></i>
                    </a>
                  </div>
                </div>
              </footer>
            </article>
          </div>
          <div class="comments" id="gitalk-container"></div>
          <script>
            window.addEventListener('tabs:register', () =>
            {
              let
              {
                activeClass
              } = CONFIG.comments;
              if (CONFIG.comments.storage)
              {
                activeClass = localStorage.getItem('comments_active') || activeClass;
              }
              if (activeClass)
              {
                let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
                if (activeTab)
                {
                  activeTab.click();
                }
              }
            });
            if (CONFIG.comments.storage)
            {
              window.addEventListener('tabs:click', event =>
              {
                if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
                let commentClass = event.target.classList[1];
                localStorage.setItem('comments_active', commentClass);
              });
            }

          </script>
        </div>
        <div class="toggle sidebar-toggle">
          <span class="toggle-line toggle-line-first"></span>
          <span class="toggle-line toggle-line-middle"></span>
          <span class="toggle-line toggle-line-last"></span>
        </div>
        <aside class="sidebar">
          <div class="sidebar-inner">
            <ul class="sidebar-nav motion-element">
              <li class="sidebar-nav-toc"> 文章目录 </li>
              <li class="sidebar-nav-overview"> 站点概览 </li>
            </ul>
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc motion-element">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#简介与特性"><span class="nav-number">2.</span> <span class="nav-text">简介与特性</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#基本用法"><span class="nav-number">3.</span> <span class="nav-text">基本用法</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#别名使用"><span class="nav-number">4.</span> <span class="nav-text">别名使用</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#声明和比较"><span class="nav-number">5.</span> <span class="nav-text">声明和比较</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#属性定义"><span class="nav-number">6.</span> <span class="nav-text">属性定义</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#属性名"><span class="nav-number">6.1.</span> <span class="nav-text">属性名</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#默认值"><span class="nav-number">6.2.</span> <span class="nav-text">默认值</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#初始化"><span class="nav-number">6.3.</span> <span class="nav-text">初始化</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#强制关键字"><span class="nav-number">6.4.</span> <span class="nav-text">强制关键字</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#验证器"><span class="nav-number">6.5.</span> <span class="nav-text">验证器</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#转换器"><span class="nav-number">6.6.</span> <span class="nav-text">转换器</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#类型"><span class="nav-number">6.7.</span> <span class="nav-text">类型</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#序列转换"><span class="nav-number">7.</span> <span class="nav-text">序列转换</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#基本转换"><span class="nav-number">7.1.</span> <span class="nav-text">基本转换</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#多类型转换"><span class="nav-number">7.2.</span> <span class="nav-text">多类型转换</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#属性处理"><span class="nav-number">7.3.</span> <span class="nav-text">属性处理</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#嵌套处理"><span class="nav-number">7.4.</span> <span class="nav-text">嵌套处理</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#结语"><span class="nav-number">8.</span> <span class="nav-text">结语</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->
            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <img class="site-author-image" itemprop="image" alt="崔庆才" src="/images/avatar.png">
                <p class="site-author-name" itemprop="name">崔庆才</p>
                <div class="site-description" itemprop="description">崔庆才的个人站点，记录生活的瞬间，分享学习的心得。</div>
              </div>
              <div class="site-state-wrap motion-element">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">
                      <span class="site-state-item-count">608</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">
                      <span class="site-state-item-count">24</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">
                      <span class="site-state-item-count">156</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author motion-element">
                <span class="links-of-author-item">
                  <a href="https://github.com/Germey" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Germey" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:cqc@cuiqingcai.com.com" title="邮件 → mailto:cqc@cuiqingcai.com.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>邮件</a>
                </span>
                <span class="links-of-author-item">
                  <a href="https://weibo.com/cuiqingcai" title="微博 → https:&#x2F;&#x2F;weibo.com&#x2F;cuiqingcai" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>微博</a>
                </span>
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/Germey" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;Germey" rel="noopener" target="_blank"><i class="fa fa-magic fa-fw"></i>知乎</a>
                </span>
              </div>
            </div>
            <div style=" width: 100%;" class="sidebar-panel sidebar-panel-image sidebar-panel-active">
              <a href="https://tutorial.lengyue.video/?coupon=12ef4b1a-a3db-11ea-bb37-0242ac130002_cqx_850" target="_blank" rel="noopener">
                <img src="https://qiniu.cuiqingcai.com/bco2a.png" style=" width: 100%;">
              </a>
            </div>
            <div style=" width: 100%;" class="sidebar-panel sidebar-panel-image sidebar-panel-active">
              <a href="http://www.ipidea.net/?utm-source=cqc&utm-keyword=?cqc" target="_blank" rel="noopener">
                <img src="https://qiniu.cuiqingcai.com/0ywun.png" style=" width: 100%;">
              </a>
            </div>
            <div class="sidebar-panel sidebar-panel-tags sidebar-panel-active">
              <h4 class="name"> 标签云 </h4>
              <div class="content">
                <a href="/tags/2048/" style="font-size: 10px;">2048</a> <a href="/tags/API/" style="font-size: 10px;">API</a> <a href="/tags/Bootstrap/" style="font-size: 11.25px;">Bootstrap</a> <a href="/tags/CDN/" style="font-size: 10px;">CDN</a> <a href="/tags/CQC/" style="font-size: 10px;">CQC</a> <a href="/tags/CSS/" style="font-size: 10px;">CSS</a> <a href="/tags/CSS-%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 10px;">CSS 反爬虫</a> <a href="/tags/CV/" style="font-size: 10px;">CV</a> <a href="/tags/Django/" style="font-size: 10px;">Django</a> <a href="/tags/Eclipse/" style="font-size: 11.25px;">Eclipse</a> <a href="/tags/FTP/" style="font-size: 10px;">FTP</a> <a href="/tags/Git/" style="font-size: 10px;">Git</a> <a href="/tags/GitHub/" style="font-size: 13.75px;">GitHub</a> <a href="/tags/HTML5/" style="font-size: 10px;">HTML5</a> <a href="/tags/Hexo/" style="font-size: 10px;">Hexo</a> <a href="/tags/IT/" style="font-size: 10px;">IT</a> <a href="/tags/JSP/" style="font-size: 10px;">JSP</a> <a href="/tags/JavaScript/" style="font-size: 10px;">JavaScript</a> <a href="/tags/K8s/" style="font-size: 10px;">K8s</a> <a href="/tags/LOGO/" style="font-size: 10px;">LOGO</a> <a href="/tags/Linux/" style="font-size: 10px;">Linux</a> <a href="/tags/MIUI/" style="font-size: 10px;">MIUI</a> <a href="/tags/MongoDB/" style="font-size: 10px;">MongoDB</a> <a href="/tags/Mysql/" style="font-size: 10px;">Mysql</a> <a href="/tags/NBA/" style="font-size: 10px;">NBA</a> <a href="/tags/PHP/" style="font-size: 11.25px;">PHP</a> <a href="/tags/PS/" style="font-size: 10px;">PS</a> <a href="/tags/Pathlib/" style="font-size: 10px;">Pathlib</a> <a href="/tags/PhantomJS/" style="font-size: 10px;">PhantomJS</a> <a href="/tags/Python/" style="font-size: 15px;">Python</a> <a href="/tags/Python3/" style="font-size: 12.5px;">Python3</a> <a href="/tags/Pythonic/" style="font-size: 10px;">Pythonic</a> <a href="/tags/QQ/" style="font-size: 10px;">QQ</a> <a href="/tags/Redis/" style="font-size: 10px;">Redis</a> <a href="/tags/SAE/" style="font-size: 10px;">SAE</a> <a href="/tags/SSH/" style="font-size: 10px;">SSH</a> <a href="/tags/SVG/" style="font-size: 10px;">SVG</a> <a href="/tags/Scrapy/" style="font-size: 10px;">Scrapy</a> <a href="/tags/Scrapy-redis/" style="font-size: 10px;">Scrapy-redis</a> <a href="/tags/Scrapy%E5%88%86%E5%B8%83%E5%BC%8F/" style="font-size: 10px;">Scrapy分布式</a> <a href="/tags/Selenium/" style="font-size: 10px;">Selenium</a> <a href="/tags/TKE/" style="font-size: 10px;">TKE</a> <a href="/tags/Ubuntu/" style="font-size: 11.25px;">Ubuntu</a> <a href="/tags/VS-Code/" style="font-size: 10px;">VS Code</a> <a href="/tags/Vs-Code/" style="font-size: 10px;">Vs Code</a> <a href="/tags/Vue/" style="font-size: 11.25px;">Vue</a> <a href="/tags/Webpack/" style="font-size: 10px;">Webpack</a> <a href="/tags/Windows/" style="font-size: 10px;">Windows</a> <a href="/tags/Winpcap/" style="font-size: 10px;">Winpcap</a> <a href="/tags/WordPress/" style="font-size: 13.75px;">WordPress</a> <a href="/tags/Youtube/" style="font-size: 11.25px;">Youtube</a> <a href="/tags/android/" style="font-size: 10px;">android</a> <a href="/tags/ansible/" style="font-size: 10px;">ansible</a> <a href="/tags/cocos2d-x/" style="font-size: 10px;">cocos2d-x</a> <a href="/tags/e6/" style="font-size: 10px;">e6</a> <a href="/tags/fitvids/" style="font-size: 10px;">fitvids</a> <a href="/tags/git/" style="font-size: 11.25px;">git</a> <a href="/tags/json/" style="font-size: 10px;">json</a> <a href="/tags/js%E9%80%86%E5%90%91/" style="font-size: 10px;">js逆向</a> <a href="/tags/kubernetes/" style="font-size: 10px;">kubernetes</a> <a href="/tags/log/" style="font-size: 10px;">log</a> <a href="/tags/logging/" style="font-size: 10px;">logging</a> <a href="/tags/matlab/" style="font-size: 11.25px;">matlab</a> <a href="/tags/python/" style="font-size: 20px;">python</a> <a href="/tags/pytube/" style="font-size: 11.25px;">pytube</a> <a href="/tags/pywin32/" style="font-size: 10px;">pywin32</a> <a href="/tags/style/" style="font-size: 10px;">style</a> <a href="/tags/tomcat/" style="font-size: 10px;">tomcat</a> <a href="/tags/ubuntu/" style="font-size: 10px;">ubuntu</a> <a href="/tags/uwsgi/" style="font-size: 10px;">uwsgi</a> <a href="/tags/vsftpd/" style="font-size: 10px;">vsftpd</a> <a href="/tags/wamp/" style="font-size: 10px;">wamp</a> <a href="/tags/wineQQ/" style="font-size: 10px;">wineQQ</a> <a href="/tags/%E4%B8%83%E7%89%9B/" style="font-size: 11.25px;">七牛</a> <a href="/tags/%E4%B8%8A%E6%B5%B7/" style="font-size: 10px;">上海</a> <a href="/tags/%E4%B8%AA%E4%BA%BA%E7%BD%91%E7%AB%99/" style="font-size: 10px;">个人网站</a> <a href="/tags/%E4%B8%BB%E9%A2%98/" style="font-size: 10px;">主题</a> <a href="/tags/%E4%BA%91%E4%BA%A7%E5%93%81/" style="font-size: 10px;">云产品</a> <a href="/tags/%E4%BA%91%E5%AD%98%E5%82%A8/" style="font-size: 10px;">云存储</a> <a href="/tags/%E4%BA%AC%E4%B8%9C%E4%BA%91/" style="font-size: 10px;">京东云</a> <a href="/tags/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/" style="font-size: 12.5px;">人工智能</a> <a href="/tags/%E4%BB%A3%E7%90%86/" style="font-size: 10px;">代理</a> <a href="/tags/%E4%BB%A3%E7%A0%81/" style="font-size: 10px;">代码</a> <a href="/tags/%E4%BB%A3%E7%A0%81%E5%88%86%E4%BA%AB%E5%9B%BE/" style="font-size: 10px;">代码分享图</a> <a href="/tags/%E4%BC%98%E5%8C%96/" style="font-size: 10px;">优化</a> <a href="/tags/%E4%BD%8D%E8%BF%90%E7%AE%97/" style="font-size: 10px;">位运算</a> <a href="/tags/%E5%85%AC%E4%BC%97%E5%8F%B7/" style="font-size: 10px;">公众号</a> <a href="/tags/%E5%88%86%E4%BA%AB/" style="font-size: 10px;">分享</a> <a href="/tags/%E5%88%86%E5%B8%83%E5%BC%8F/" style="font-size: 10px;">分布式</a> <a href="/tags/%E5%88%9B%E4%B8%9A/" style="font-size: 10px;">创业</a> <a href="/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 12.5px;">前端</a> <a href="/tags/%E5%8D%9A%E5%AE%A2/" style="font-size: 10px;">博客</a> <a href="/tags/%E5%8E%9F%E7%94%9FAPP/" style="font-size: 10px;">原生APP</a> <a href="/tags/%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 12.5px;">反爬虫</a> <a href="/tags/%E5%91%BD%E4%BB%A4/" style="font-size: 10px;">命令</a> <a href="/tags/%E5%93%8D%E5%BA%94%E5%BC%8F%E5%B8%83%E5%B1%80/" style="font-size: 10px;">响应式布局</a> <a href="/tags/%E5%9E%83%E5%9C%BE%E9%82%AE%E4%BB%B6/" style="font-size: 10px;">垃圾邮件</a> <a href="/tags/%E5%9F%9F%E5%90%8D%E7%BB%91%E5%AE%9A/" style="font-size: 10px;">域名绑定</a> <a href="/tags/%E5%A4%8D%E7%9B%98/" style="font-size: 10px;">复盘</a> <a href="/tags/%E5%A4%A7%E4%BC%97%E7%82%B9%E8%AF%84/" style="font-size: 10px;">大众点评</a> <a href="/tags/%E5%AD%97%E4%BD%93%E5%8F%8D%E7%88%AC%E8%99%AB/" style="font-size: 10px;">字体反爬虫</a> <a href="/tags/%E5%AD%97%E7%AC%A6%E9%97%AE%E9%A2%98/" style="font-size: 10px;">字符问题</a> <a href="/tags/%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95/" style="font-size: 10px;">学习方法</a> <a href="/tags/%E5%AE%89%E5%8D%93/" style="font-size: 10px;">安卓</a> <a href="/tags/%E5%AE%9E%E7%94%A8/" style="font-size: 10px;">实用</a> <a href="/tags/%E5%B0%81%E9%9D%A2/" style="font-size: 10px;">封面</a> <a href="/tags/%E5%B4%94%E5%BA%86%E6%89%8D/" style="font-size: 18.75px;">崔庆才</a> <a href="/tags/%E5%B7%A5%E5%85%B7/" style="font-size: 12.5px;">工具</a> <a href="/tags/%E5%BC%80%E5%8F%91%E5%B7%A5%E5%85%B7/" style="font-size: 10px;">开发工具</a> <a href="/tags/%E5%BE%AE%E8%BD%AF/" style="font-size: 10px;">微软</a> <a href="/tags/%E6%80%9D%E8%80%83/" style="font-size: 10px;">思考</a> <a href="/tags/%E6%89%8B%E6%9C%BA%E8%AE%BF%E9%97%AE/" style="font-size: 10px;">手机访问</a> <a href="/tags/%E6%95%99%E7%A8%8B/" style="font-size: 10px;">教程</a> <a href="/tags/%E6%95%99%E8%82%B2/" style="font-size: 10px;">教育</a> <a href="/tags/%E6%96%B0%E4%B9%A6/" style="font-size: 12.5px;">新书</a> <a href="/tags/%E6%96%B9%E6%B3%95%E8%AE%BA/" style="font-size: 10px;">方法论</a> <a href="/tags/%E6%97%85%E6%B8%B8/" style="font-size: 10px;">旅游</a> <a href="/tags/%E6%97%A5%E5%BF%97/" style="font-size: 10px;">日志</a> <a href="/tags/%E6%9A%97%E6%97%B6%E9%97%B4/" style="font-size: 10px;">暗时间</a> <a href="/tags/%E6%9D%9C%E5%85%B0%E7%89%B9/" style="font-size: 11.25px;">杜兰特</a> <a href="/tags/%E6%A1%8C%E9%9D%A2/" style="font-size: 10px;">桌面</a> <a href="/tags/%E6%AD%8C%E5%8D%95/" style="font-size: 10px;">歌单</a> <a href="/tags/%E6%B1%9F%E5%8D%97/" style="font-size: 10px;">江南</a> <a href="/tags/%E6%B8%B8%E6%88%8F/" style="font-size: 10px;">游戏</a> <a href="/tags/%E7%84%A6%E8%99%91/" style="font-size: 10px;">焦虑</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 16.25px;">爬虫</a> <a href="/tags/%E7%88%AC%E8%99%AB%E4%B9%A6%E7%B1%8D/" style="font-size: 11.25px;">爬虫书籍</a> <a href="/tags/%E7%8E%AF%E5%A2%83%E5%8F%98%E9%87%8F/" style="font-size: 10px;">环境变量</a> <a href="/tags/%E7%94%9F%E6%B4%BB%E7%AC%94%E8%AE%B0/" style="font-size: 10px;">生活笔记</a> <a href="/tags/%E7%99%BB%E5%BD%95/" style="font-size: 10px;">登录</a> <a href="/tags/%E7%9F%A5%E4%B9%8E/" style="font-size: 10px;">知乎</a> <a href="/tags/%E7%9F%AD%E4%BF%A1/" style="font-size: 10px;">短信</a> <a href="/tags/%E7%9F%AD%E4%BF%A1%E9%AA%8C%E8%AF%81%E7%A0%81/" style="font-size: 10px;">短信验证码</a> <a href="/tags/%E7%AC%94%E8%AE%B0%E8%BD%AF%E4%BB%B6/" style="font-size: 10px;">笔记软件</a> <a href="/tags/%E7%AF%AE%E7%BD%91/" style="font-size: 10px;">篮网</a> <a href="/tags/%E7%BA%B8%E5%BC%A0/" style="font-size: 10px;">纸张</a> <a href="/tags/%E7%BB%84%E4%BB%B6/" style="font-size: 10px;">组件</a> <a href="/tags/%E7%BD%91%E7%AB%99/" style="font-size: 10px;">网站</a> <a href="/tags/%E7%BD%91%E7%BB%9C%E7%88%AC%E8%99%AB/" style="font-size: 11.25px;">网络爬虫</a> <a href="/tags/%E7%BE%8E%E5%AD%A6/" style="font-size: 10px;">美学</a> <a href="/tags/%E8%82%89%E5%A4%B9%E9%A6%8D/" style="font-size: 10px;">肉夹馍</a> <a href="/tags/%E8%85%BE%E8%AE%AF%E4%BA%91/" style="font-size: 10px;">腾讯云</a> <a href="/tags/%E8%87%AA%E5%BE%8B/" style="font-size: 10px;">自律</a> <a href="/tags/%E8%A5%BF%E5%B0%91%E7%88%B7/" style="font-size: 10px;">西少爷</a> <a href="/tags/%E8%A7%86%E9%A2%91/" style="font-size: 10px;">视频</a> <a href="/tags/%E8%B0%B7%E6%AD%8C%E9%AA%8C%E8%AF%81%E7%A0%81/" style="font-size: 10px;">谷歌验证码</a> <a href="/tags/%E8%BF%90%E8%90%A5/" style="font-size: 10px;">运营</a> <a href="/tags/%E8%BF%9C%E7%A8%8B/" style="font-size: 10px;">远程</a> <a href="/tags/%E9%80%86%E5%90%91/" style="font-size: 10px;">逆向</a> <a href="/tags/%E9%85%8D%E7%BD%AE/" style="font-size: 10px;">配置</a> <a href="/tags/%E9%87%8D%E8%A3%85/" style="font-size: 10px;">重装</a> <a href="/tags/%E9%98%BF%E6%9D%9C/" style="font-size: 10px;">阿杜</a> <a href="/tags/%E9%9D%99%E8%A7%85/" style="font-size: 17.5px;">静觅</a> <a href="/tags/%E9%A2%A0%E8%A6%86/" style="font-size: 10px;">颠覆</a> <a href="/tags/%E9%A3%9E%E4%BF%A1/" style="font-size: 10px;">飞信</a> <a href="/tags/%E9%B8%BF%E8%92%99/" style="font-size: 10px;">鸿蒙</a>
              </div>
              <script>
                const tagsColors = ['#00a67c', '#5cb85c', '#d9534f', '#567e95', '#b37333', '#f4843d', '#15a287']
                const tagsElements = document.querySelectorAll('.sidebar-panel-tags .content a')
                tagsElements.forEach((item) =>
                {
                  item.style.backgroundColor = tagsColors[Math.floor(Math.random() * tagsColors.length)]
                })

              </script>
            </div>
            <div class="sidebar-panel sidebar-panel-categories sidebar-panel-active">
              <h4 class="name"> 分类 </h4>
              <div class="content">
                <ul class="category-list">
                  <li class="category-list-item"><a class="category-list-link" href="/categories/C-C/">C/C++</a><span class="category-list-count">23</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/HTML/">HTML</a><span class="category-list-count">14</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">5</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">26</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">15</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Markdown/">Markdown</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Net/">Net</a><span class="category-list-count">4</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Other/">Other</a><span class="category-list-count">39</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">27</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Paper/">Paper</a><span class="category-list-count">2</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/Python/">Python</a><span class="category-list-count">261</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/TypeScript/">TypeScript</a><span class="category-list-count">2</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E5%B1%95%E7%A4%BA/">个人展示</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E6%97%A5%E8%AE%B0/">个人日记</a><span class="category-list-count">9</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E8%AE%B0%E5%BD%95/">个人记录</a><span class="category-list-count">4</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E4%B8%AA%E4%BA%BA%E9%9A%8F%E7%AC%94/">个人随笔</a><span class="category-list-count">15</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E5%AE%89%E8%A3%85%E9%85%8D%E7%BD%AE/">安装配置</a><span class="category-list-count">59</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E6%8A%80%E6%9C%AF%E6%9D%82%E8%B0%88/">技术杂谈</a><span class="category-list-count">88</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E6%9C%AA%E5%88%86%E7%B1%BB/">未分类</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E7%94%9F%E6%B4%BB%E7%AC%94%E8%AE%B0/">生活笔记</a><span class="category-list-count">1</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E7%A6%8F%E5%88%A9%E4%B8%93%E5%8C%BA/">福利专区</a><span class="category-list-count">6</span></li>
                  <li class="category-list-item"><a class="category-list-link" href="/categories/%E8%81%8C%E4%BD%8D%E6%8E%A8%E8%8D%90/">职位推荐</a><span class="category-list-count">2</span></li>
                </ul>
              </div>
            </div>
            <div class="sidebar-panel sidebar-panel-friends sidebar-panel-active">
              <h4 class="name"> 友情链接 </h4>
              <ul class="friends">
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/j2dub.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.findhao.net/" target="_blank" rel="noopener">FindHao</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ou6mm.jpg">
                  </span>
                  <span class="link">
                    <a href="https://diygod.me/" target="_blank" rel="noopener">DIYgod</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/6apxu.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.51dev.com/" target="_blank" rel="noopener">IT技术社区</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.jankl.com/img/titleshu.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.jankl.com/" target="_blank" rel="noopener">liberalist</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/bqlbs.png">
                  </span>
                  <span class="link">
                    <a href="http://www.urselect.com/" target="_blank" rel="noopener">优社电商</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/8s88c.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.yuanrenxue.com/" target="_blank" rel="noopener">猿人学</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/2wgg5.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.yunlifang.cn/" target="_blank" rel="noopener">云立方</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/shwr6.png">
                  </span>
                  <span class="link">
                    <a href="http://lanbing510.info/" target="_blank" rel="noopener">冰蓝</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/blvoh.jpg">
                  </span>
                  <span class="link">
                    <a href="https://lengyue.me/" target="_blank" rel="noopener">冷月</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="http://qianxunclub.com/favicon.png">
                  </span>
                  <span class="link">
                    <a href="http://qianxunclub.com/" target="_blank" rel="noopener">千寻啊千寻</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/0044u.jpg">
                  </span>
                  <span class="link">
                    <a href="http://kodcloud.com/" target="_blank" rel="noopener">可道云</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ygnpn.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.kunkundashen.cn/" target="_blank" rel="noopener">坤坤大神</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/22uv1.png">
                  </span>
                  <span class="link">
                    <a href="http://www.cenchong.com/" target="_blank" rel="noopener">岑冲博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ev9kl.png">
                  </span>
                  <span class="link">
                    <a href="http://www.zxiaoji.com/" target="_blank" rel="noopener">张小鸡</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.503error.com/favicon.ico">
                  </span>
                  <span class="link">
                    <a href="https://www.503error.com/" target="_blank" rel="noopener">张志明个人博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/x714o.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.hubwiz.com/" target="_blank" rel="noopener">汇智网</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/129d8.png">
                  </span>
                  <span class="link">
                    <a href="https://www.bysocket.com/" target="_blank" rel="noopener">泥瓦匠BYSocket</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://www.xiongge.club/favicon.ico">
                  </span>
                  <span class="link">
                    <a href="https://www.xiongge.club/" target="_blank" rel="noopener">熊哥club</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/3w4fe.png">
                  </span>
                  <span class="link">
                    <a href="https://zerlong.com/" target="_blank" rel="noopener">知语</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/44hxf.png">
                  </span>
                  <span class="link">
                    <a href="http://redstonewill.com/" target="_blank" rel="noopener">红色石头</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/8g1fk.jpg">
                  </span>
                  <span class="link">
                    <a href="http://www.laodong.me/" target="_blank" rel="noopener">老董博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/wkaus.jpg">
                  </span>
                  <span class="link">
                    <a href="https://zhaoshuai.me/" target="_blank" rel="noopener">碎念</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/pgo0r.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.chenwenguan.com/" target="_blank" rel="noopener">陈文管的博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/kk82a.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.lxlinux.net/" target="_blank" rel="noopener">良许Linux教程网</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/lj0t2.jpg">
                  </span>
                  <span class="link">
                    <a href="https://tanqingbo.cn/" target="_blank" rel="noopener">IT码农</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/i8cdr.png">
                  </span>
                  <span class="link">
                    <a href="https://junyiseo.com/" target="_blank" rel="noopener">均益个人博客</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/chwv2.png">
                  </span>
                  <span class="link">
                    <a href="https://brucedone.com/" target="_blank" rel="noopener">大鱼的鱼塘</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/2y43o.png">
                  </span>
                  <span class="link">
                    <a href="http://bbs.nightteam.cn/" target="_blank" rel="noopener">夜幕爬虫安全论坛</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/zvc3w.jpg">
                  </span>
                  <span class="link">
                    <a href="https://www.weishidong.com/" target="_blank" rel="noopener">韦世东的技术专栏</a>
                  </span>
                </li>
                <li class="friend">
                  <span class="logo">
                    <img src="https://qiniu.cuiqingcai.com/ebudy.jpg">
                  </span>
                  <span class="link">
                    <a href="https://chuanjiabing.com/" target="_blank" rel="noopener">穿甲兵技术社区</a>
                  </span>
                </li>
              </ul>
            </div>
          </div>
        </aside>
        <div id="sidebar-dimmer"></div>
      </div>
    </main>
    <footer class="footer">
      <div class="footer-inner">
        <div class="copyright"> &copy; <span itemprop="copyrightYear">2021</span>
          <span class="with-love">
            <i class="fa fa-heart"></i>
          </span>
          <span class="author" itemprop="copyrightHolder">崔庆才丨静觅</span>
          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-chart-area"></i>
          </span>
          <span title="站点总字数">2.6m</span>
          <span class="post-meta-divider">|</span>
          <span class="post-meta-item-icon">
            <i class="fa fa-coffee"></i>
          </span>
          <span title="站点阅读时长">39:54</span>
        </div>
        <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动 </div>
        <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">京ICP备18015597号-1 </a>
        </div>
        <script>
          (function ()
          {
            function leancloudSelector(url)
            {
              url = encodeURI(url);
              return document.getElementById(url).querySelector('.leancloud-visitors-count');
            }

            function addCount(Counter)
            {
              var visitors = document.querySelector('.leancloud_visitors');
              var url = decodeURI(visitors.id);
              var title = visitors.dataset.flagTitle;
              Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify(
              {
                url
              }))).then(response => response.json()).then((
              {
                results
              }) =>
              {
                if (results.length > 0)
                {
                  var counter = results[0];
                  leancloudSelector(url).innerText = counter.time + 1;
                  Counter('put', '/classes/Counter/' + counter.objectId,
                  {
                    time:
                    {
                      '__op': 'Increment',
                      'amount': 1
                    }
                  }).catch(error =>
                  {
                    console.error('Failed to save visitor count', error);
                  });
                }
                else
                {
                  Counter('post', '/classes/Counter',
                  {
                    title,
                    url,
                    time: 1
                  }).then(response => response.json()).then(() =>
                  {
                    leancloudSelector(url).innerText = 1;
                  }).catch(error =>
                  {
                    console.error('Failed to create', error);
                  });
                }
              }).catch(error =>
              {
                console.error('LeanCloud Counter Error', error);
              });
            }

            function showTime(Counter)
            {
              var visitors = document.querySelectorAll('.leancloud_visitors');
              var entries = [...visitors].map(element =>
              {
                return decodeURI(element.id);
              });
              Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify(
              {
                url:
                {
                  '$in': entries
                }
              }))).then(response => response.json()).then((
              {
                results
              }) =>
              {
                for (let url of entries)
                {
                  let target = results.find(item => item.url === url);
                  leancloudSelector(url).innerText = target ? target.time : 0;
                }
              }).catch(error =>
              {
                console.error('LeanCloud Counter Error', error);
              });
            }
            let
            {
              app_id,
              app_key,
              server_url
            } = {
              "enable": true,
              "app_id": "6X5dRQ0pnPWJgYy8SXOg0uID-gzGzoHsz",
              "app_key": "ziLDVEy73ne5HtFTiGstzHMS",
              "server_url": "https://6x5drq0p.lc-cn-n1-shared.com",
              "security": false
            };

            function fetchData(api_server)
            {
              var Counter = (method, url, data) =>
              {
                return fetch(`${api_server}/1.1${url}`,
                {
                  method,
                  headers:
                  {
                    'X-LC-Id': app_id,
                    'X-LC-Key': app_key,
                    'Content-Type': 'application/json',
                  },
                  body: JSON.stringify(data)
                });
              };
              if (CONFIG.page.isPost)
              {
                if (CONFIG.hostname !== location.hostname) return;
                addCount(Counter);
              }
              else if (document.querySelectorAll('.post-title-link').length >= 1)
              {
                showTime(Counter);
              }
            }
            let api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;
            if (api_server)
            {
              fetchData(api_server);
            }
            else
            {
              fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id).then(response => response.json()).then((
              {
                api_server
              }) =>
              {
                fetchData('https://' + api_server);
              });
            }
          })();

        </script>
      </div>
      <div class="footer-stat">
        <span id="cnzz_stat_icon_1279355174"></span>
        <script type="text/javascript">
          document.write(unescape("%3Cspan id='cnzz_stat_icon_1279355174'%3E%3C/span%3E%3Cscript src='https://v1.cnzz.com/z_stat.php%3Fid%3D1279355174%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));

        </script>
      </div>
    </footer>
  </div>
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/.js"></script>
  <script src="/js/schemes/pisces.js"></script>
  <script src="/.js"></script>
  <script src="/js/next-boot.js"></script>
  <script src="/.js"></script>
  <script>
    (function ()
    {
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x = document.getElementsByTagName("link");
      //Find the last canonical URL
      if (x.length > 0)
      {
        for (i = 0; i < x.length; i++)
        {
          if (x[i].rel.toLowerCase() == 'canonical' && x[i].href)
          {
            canonicalURL = x[i].href;
          }
        }
      }
      //Get protocol
      if (!canonicalURL)
      {
        curProtocol = window.location.protocol.split(':')[0];
      }
      else
      {
        curProtocol = canonicalURL.split(':')[0];
      }
      //Get current URL if the canonical URL does not exist
      if (!canonicalURL) canonicalURL = window.location.href;
      //Assign script content. Replace current URL with the canonical URL
      ! function ()
      {
        var e = /([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,
          r = canonicalURL,
          t = document.referrer;
        if (!e.test(r))
        {
          var n = (String(curProtocol).toLowerCase() === 'https') ? "https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif" : "//api.share.baidu.com/s.gif";
          t ? (n += "?r=" + encodeURIComponent(document.referrer), r && (n += "&l=" + r)) : r && (n += "?l=" + r);
          var i = new Image;
          i.src = n
        }
      }(window);
    })();

  </script>
  <script src="/js/local-search.js"></script>
  <script src="/.js"></script>
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">
  <script>
    NexT.utils.loadComments(document.querySelector('#gitalk-container'), () =>
    {
      NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () =>
      {
        var gitalk = new Gitalk(
        {
          clientID: '4c86ce1d7c4fbb3b277c',
          clientSecret: '4927beb0f90e2c07e66c99d9d2529cf3eb8ac8e4',
          repo: 'Blog',
          owner: 'germey',
          admin: ['germey'],
          id: 'c8198764a677675c5ba6f1f8fc660596',
          language: 'zh-CN',
          distractionFreeMode: true
        });
        gitalk.render('gitalk-container');
      }, window.Gitalk);
    });

  </script>
</body>

</html>
